package z.ftpc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;

public final class MainActivity extends Activity {

    private static String hostname = "0.0.0.0";
    private static int port = 2121;
    public static FTPClient client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText ip = findViewById(R.id.ip);
        EditText dk = findViewById(R.id.dk);
        ip.setText(hostname);
        dk.setText(port + "");

        ip.addTextChangedListener(textWatcher(s -> hostname = s));

        dk.addTextChangedListener(textWatcher(s -> {
            if (!s.equals("")) port = Integer.parseInt(s);
        }));
    }

    public void onClick(View view) {
        client = new FTPClient();
        client.setControlEncoding("utf-8");
        try {
            client.connect(hostname, port);
            client.login("anonymous", null);
            popup("连接成功");
            startActivity(new Intent(this, FileActivity.class));
        } catch (IOException e) {
            popup("连接失败："+e.getMessage());
        }

    }

    private void popup(String tip) {
        Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
    }

    private interface ITextWatcher {
        void afterTextChanged(String s);
    }

    private TextWatcher textWatcher(final ITextWatcher textWatcher) {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                textWatcher.afterTextChanged(editable.toString());
            }
        };
    }

}
